package com.ciwong.epaper.modules.epaper.ui;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.cordva.bean.AddErrbookResponce;
import com.ciwong.epaper.modules.cordva.bean.ErrorBook;
import com.ciwong.epaper.modules.cordva.bean.ErrorBookJson;
import com.ciwong.epaper.modules.cordva.bean.QusetionBean;
import com.ciwong.epaper.modules.cordva.dao.CordvaDao;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.TeacherCommentDialog;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.bean.Main;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BrowserActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 做作业浏览器 Created by pla-gysu on 2015/7/29.
 */
public class DoWorkBrowerActivity extends BrowserActivity
        implements BrowserActivity.LoadCallback
{
    private int jumpType;

    private DownLoadInfo downLoadInfo;

    private Module mModule;

    private int position;

    private String uuid;

    private String doWorkId;

    private String checkedResource;

    private String correctAnswer;

    private  String mTeacherComment;

    @Override
    public void preCreate()
    {
        Intent intent = getIntent();
        if (intent != null)
        {
            setLoadCallback(this);
            jumpType = intent.getIntExtra(IntentString.INTENT_STRING_TYPE,
                    BrowerJumpType.TYPE_ASSEY);
            mModule = (Module) intent
                    .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            downLoadInfo = (DownLoadInfo) intent
                    .getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
            uuid = intent.getStringExtra(IntentFlag.INTENT_FLAG_UUID);
            doWorkId = intent.getStringExtra(IntentFlag.INTENT_FLAG_ID);
            checkedResource = intent
                    .getStringExtra(IntentFlag.INTENT_FLAG_CHECKED_RESOURCE);

            intent.putExtra(IntentString.INTENT_STRING_URL,
                    jumpType == BrowerJumpType.TYPE_ASSEY
                            ? EConstants.LOCAL_HTML_PATH
                            : EConstants.LOCAL_HTML_PATH_LS_ANSWER);
           //intent.putExtra(IntentString.INTENT_STRING_URL,"file://" + ESystem.getErrorBookPath() + File.separator + "errorBook.html");
            super.preCreate();
        }
    }


    @Override
    public void init() {
        super.init();
        //不用原封装在基类的，因为无响应bug


        //为什么要把按钮放在这里设置，因为在showMiddleProgressBar 之前会把按钮又隐藏掉，由于不熟悉代码，暂时不敢大改--neo
        final Answer answer = (Answer) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_ANSWER);

        if(answer != null && null != answer.getComment() && answer.getComment().length() > 0)
        {
            mTeacherComment=answer.getComment();
        }else {
            mTeacherComment=getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TEACHER_COMMENT);
        }



//        if (null != answer) {
//            hideTitleBar();
//            browser_title_bar.setVisibility(View.VISIBLE);
//            browser_title_bar.setTitle(answer.getResourceName());
//
//            browser_title_bar.setBackListener(new ViewOnClickListener() {
//                @Override
//                public void avertRepeatOnClick(View v) {
//                    finish();
//                }
//            });
//        }

        if (null != mTeacherComment&& mTeacherComment.length() > 0) {
            setRightBtnBG(R.mipmap.icon_teacher_comment);
            setRightBtnEnable(true);
            setRightBtnListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    DialogUtil.showCommentDialog(DoWorkBrowerActivity.this,mTeacherComment);
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onLoadOver()
    {

        if (jumpType == BrowerJumpType.TYPE_ASSEY)
        {
            getResult(ESystem.getPackagesPath(DoWorkBrowerActivity.this) + File.separator + mModule
                    .getResourceList().get(position).getResourceFile());
        }
        else
        {

            showMiddleProgressBar(getTitleText());



            SerializableManager.getInstance().deSerialize(
                    SerializableManager.SerializeKey.SHARE_KEY_LISTEN_SPEAK_WORK_CORRECT_ANSWER
                            + doWorkId,
                    new BaseCallBack()
                    {


                        @Override
                        public void failed(int errorCode, Object data)
                        {

                            MeDao.getInstance().getListenWorkCorrect(doWorkId,
                                    new BaseExtCallBack(DoWorkBrowerActivity.this,EApplication.getInstance().getUserInfoBase().getUserId()+"")
                                    {



                                        @Override
                                        public void failed(int errorCode,
                                                Object data)
                                        {
                                           super.failed(errorCode, data);
                                            lookDetail();
                                        }

                                        @Override
                                        public void failed(Object data)
                                        {
                                            failed(-5, null);
                                        }

                                        @Override
                                        public void success(Object data)
                                        {
                                            String s = String.valueOf(data);
                                            if (!TextUtils.isEmpty(s)
                                                    && s.length() != 2)
                                            {
                                                correctAnswer = s;
                                            }
                                            lookDetail();
                                        }
                                    });
                        }

                        @Override
                        public void failed(Object data)
                        {
                            failed(-5, null);
                        }

                        @Override
                        public void success(Object data)
                        {
                            String s = String.valueOf(data);
                            if (TextUtils.isEmpty(s) || s.length() == 2)
                            {
                                failed(-5, null);
                            }
                            else
                            {
                                correctAnswer = s;
                                lookDetail();
                            }
                        }
                    });
        }



    }




    @Override
    public void onBackFinish()
    {

    }

    /**
     * 查看详情
     */
    private void lookDetail()
    {
        String mainPath = ESystem.getPackagesMainJsonPath(
                downLoadInfo.getBookId(), downLoadInfo.getChapterId());
        EpaperDao.getInstance().getSerializableObjects(mainPath, Main.class,
                new BaseExtCallBack(DoWorkBrowerActivity.this,EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {



                    @Override
                    public void failed(Object data)
                    {
                        showToastError((int) data);
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data)
                    {
                        if (isFinishing())
                        {
                            return;
                        }
                        Main main = (Main) data;
                        getCatalogueFile(main.getCatalogueFile());
                    }
                });
    }

    private void getCatalogueFile(String path)
    {
        path = ESystem.getPackagesPath(DoWorkBrowerActivity.this) + File.separator + path;
        EpaperDao.getInstance().getSerializableObjects(path,
                new TypeToken<List<Module>>()
                {
                }.getType(), new BaseExtCallBack(DoWorkBrowerActivity.this,EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {



                    @Override
                    public void failed(Object data)
                    {
                        showToastError((int) data);
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void success(Object data)
                    {
                        if (isFinishing())
                        {
                            return;
                        }
                        List<Module> modules = (List<Module>) data;

                        ModuleContent moduleContent = getModuleByModuleId(
                                modules);
                        if (moduleContent != null)
                        {
                            String resFile = moduleContent.getResourceFile();
                            String guid = resFile.substring(
                                    resFile.lastIndexOf("/") + 1,
                                    resFile.lastIndexOf("_"));
                            resFile = resFile.replace(guid,
                                    "e9430760-9f2e-4256-af76-3bd8980a9de4");
                            getResult(ESystem.getPackagesJsonPath(resFile));
                        }
                    }
                });
    }

    /**
     * 获取Module
     *
     * @param modules
     * @return
     */
    private ModuleContent getModuleByModuleId(List<Module> modules)
    {
        for (Module module : modules)
        {
            if (module.getModuleInfo().getModuleId() == mModule.getModuleInfo()
                    .getModuleId())
            {
                List<ModuleContent> resourceList = module.getResourceList();
                List<ModuleContent> resourceList1 = mModule.getResourceList();
                for (ModuleContent moduleContent : resourceList)
                {
                    int indexOf = resourceList1.indexOf(moduleContent);
                    if (indexOf >= 0)
                    {
                        return moduleContent;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取网页展示内容
     *
     * @param path
     */
    private void getResult(final String path)
    {
        EpaperDao.getInstance().getResource(path, new BaseExtCallBack(DoWorkBrowerActivity.this,EApplication.getInstance().getUserInfoBase().getUserId()+"")
        {




            @Override
            public void success(final Object data)
            {
                if (isFinishing())
                {
                    return;
                }
                if (getmWebView() != null)
                {
                    String result = ESystem.formatJsonStr(data.toString());


                    if (jumpType == BrowerJumpType.TYPE_ASSEY)
                    {
                        getmWebView().loadUrl("javascript:callback(" + result + ")");
                    }
                    else
                    {
                        // getmWebView().loadUrl("javascript:callback('"
                        // + result + "','" + "" + "')");
                        getAnswerJson(result);
                    }
                }
            }

            @Override
            public void failed(int errorCode, Object data)
            {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data)
            {
                showToastError((int) data);
            }
        });
    }

    /**
     * 获取答案json
     *
     */
    private void getAnswerJson(final String result)
    {
        EpaperDao.getInstance().getResource(
                ESystem.getAnswersUserAnswerPath(uuid), new BaseExtCallBack(DoWorkBrowerActivity.this,EApplication.getInstance().getUserInfoBase().getUserId()+"")
                {



                    @Override
                    public void success(final Object data)
                    {
                        if (isFinishing())
                        {
                            return;
                        }
                        checkedResource = TextUtils.isEmpty(checkedResource)
                                ? "" : checkedResource;
                        String answer = TextUtils.isEmpty(correctAnswer)
                                ? ESystem.formatJsonStr(data.toString())
                                : correctAnswer;

                        getmWebView().loadUrl("javascript:callback(" + result
                                + "," + answer + ",'"
                                + ESystem.getAnswersUuidPath(uuid)
                                + File.separator + "','" + checkedResource
                                + "')");


                        if (data == null)
                        {
                            showToastError(R.string.resource_file_not_exist);
                        }
                        hideMiddleProgressBar();
                    }

                    @Override
                    public void failed(int errorCode, Object data)
                    {
                        super.failed(errorCode, data);
                    }

                    @Override
                    public void failed(Object data)
                    {
                        if (isFinishing())
                        {
                            return;
                        }
                        getmWebView().loadUrl(
                                "javascript:callback('" + result + "','')");
                        showToastError((int) data);
                        finish();
                    }
                });
    }




    /**
     * 跳转类型
     *
     */
    public class BrowerJumpType
    {
        /**
         * 时文网页展示
         */
        public static final int TYPE_ASSEY = 1;

        /**
         * 听说模考查看本地答案网页
         */
        public static final int TYPE_LS_ANSWER = 2;

    }
}
